﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WareHouse.App
{
    using System.Collections;
    using System.Drawing.Printing;

    using DevExpress.XtraGrid;
    using DevExpress.XtraPrinting;
    using DevExpress.XtraPrinting.Control;

    using WareHouse.Contract.Models;
    using WareHouse.Contract.Services;
    using WareHouse.Service.Services;

    public partial class FrmManageCustomerDebt : Form
    {
        private IWareHouseService wareHouseService;

        private List<DetailCustomerPaidHistoryModel> listDetailCustomerPaidHistory;

        private CustomerPaidHistoryModel customerPaidHistoryModel;

        private List<ExportModel> listExportModel;
        private List<CustomerDebtModel> listCustomerDebtModel;

        private decimal totalAmount = 0;
        public FrmManageCustomerDebt()
        {
            listCustomerDebtModel=new List<CustomerDebtModel>();
            wareHouseService=new WareHouseService();
            InitializeComponent();
            this.CreateSummaryForGrid();
        }

        private void panel5_Paint(object sender, PaintEventArgs e)
        {

        }

        private void FrmManageCustomerDebt_Load(object sender, EventArgs e)
        {
            gridCustomer.DataSource = wareHouseService.ListCustomer();

            General.DebtDateFrom = null;
            General.DebtDateTo = null;
            General.TotalDebt = 0;
            General.TotalFromTo = 0;
            General.TotalOldAndNew = 0;
            General.TotalOldDebt = 0;
            General.TotalPaid = 0;

        }

  

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
               var modelCustomer = (CustomerModel)gridView1.GetRow(gridView1.GetSelectedRows()[0]);
               if (modelCustomer != null)
                {
                    lblCustomerName.Text = modelCustomer.FullName;
                    lblCustomerId.Text = modelCustomer.CustomerId.ToString();

                    this.LoadAllItemByCustomerId(modelCustomer.CustomerId);
                    this.UpdateLabelTotal(modelCustomer.CustomerId);
                    this.GetHistoryCustomerPaid(modelCustomer.CustomerId);
                    btnEndDebt.Enabled = true;
                }
            }
            catch (Exception)
            {


            }
        }

        private void GetHistoryCustomerPaid(int customerId)
        {
            gridHistory.DataSource = wareHouseService.GetCustomerPaidHistoryByCustomerId(customerId);
        }
        private decimal total = 0;

        private decimal totalPaid = 0;
        private void UpdateLabelTotal(int customerId)
        {
            total = this.wareHouseService.GetTotalDebt(customerId);
            totalPaid = this.wareHouseService.GetTotalCustomerPaidButNotEnd(customerId);
            this.lblTotal.Text = total.ToString("N0") + " VND";
            this.lblTotalPaid.Text = totalPaid.ToString("N0") + " VND";
            this.lblTotalDebt.Text = (total - totalPaid).ToString("N0") + " VND";
            decimal currentDebt = 0;
            // nợ hiện tại thống kê trên grid
            var gridColumnSummaryItemCollection = this.gridView2.Columns["TotalWithTax"].Summary;
            if (gridColumnSummaryItemCollection != null)
            {
                currentDebt = (decimal)gridColumnSummaryItemCollection[1].SummaryValue;
            }

            General.TotalDebt = total - totalPaid;
            General.TotalPaid = totalPaid;
            General.TotalFromTo = currentDebt;
            General.TotalOldAndNew = total;
            General.TotalOldDebt = total - currentDebt;

            this.CreateSummaryForGrid();
            
        }

        private void LoadAllItemByCustomerId(int customerId)
        {
            listCustomerDebtModel = this.wareHouseService.ListItemByCustomerId(customerId);
            this.gridItem.DataSource = listCustomerDebtModel.ToArray();
            totalAmount = listCustomerDebtModel.Sum(x => x.TotalWithTax);

            if (listCustomerDebtModel.Count > 0)
            {
                General.DebtDateFrom = listCustomerDebtModel.Select(x => x.DateCreate).Distinct().Min(x => x.Date).Date;
                General.DebtDateTo = listCustomerDebtModel.Select(x => x.DateCreate).Distinct().Max(x => x.Date).Date;

            }
         
        }
        private void LoadItemByCustomerIdInArrange(int customerId, DateTime effectiveFrom, DateTime effectiveTo)
        {
            var listResult=this.wareHouseService.ListItemByCustomerId(customerId,effectiveFrom,effectiveTo).ToArray();
            listCustomerDebtModel =new List<CustomerDebtModel>(listResult);
            this.gridItem.DataSource = listResult;
            totalAmount = listResult.Sum(x => x.TotalWithTax);

            General.DebtDateFrom = effectiveFrom;
            General.DebtDateTo = effectiveTo;

       
        }

        private void rdbArrange_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbArrange.Checked)
            {
                groupArrange.Visible = true;
            }
            else
            {
                groupArrange.Visible = false;

            }
        }

        private void btnExcute_Click(object sender, EventArgs e)
        {
            
            if (rdbArrange.Checked)
            {
                if (lblCustomerId.Text == "")
                {
                    MessageBox.Show("Chọn khách hàng");
                    return;
                }
                if (dtpFrom.EditValue == null || dtpTo.EditValue == null)
                {
                    MessageBox.Show("Chọn ngày cần liệt kê");
                    return;
                }
                var fromDate = DateTime.Parse(dtpFrom.EditValue.ToString());
                var toDate = DateTime.Parse(dtpTo.EditValue.ToString());

                this.LoadItemByCustomerIdInArrange(int.Parse(lblCustomerId.Text), fromDate, toDate);

                if (lblCustomerId.Text.Trim() != "")
                {
                    UpdateLabelTotal(int.Parse(lblCustomerId.Text));
                }

                btnEndDebt.Enabled = true;

            }
            else
            {

                if (lblCustomerId.Text == "")
                {
                    MessageBox.Show("Chọn khách hàng");
                    return;
                }
            
             
                this.LoadAllItemByCustomerId(int.Parse(lblCustomerId.Text));

                if (lblCustomerId.Text.Trim() != "")
                {
                    UpdateLabelTotal(int.Parse(lblCustomerId.Text));
                }

                btnEndDebt.Enabled = true;
            }

          
        }
        private void printLink_CreateReportHeaderArea(object sender, DevExpress.XtraPrinting.CreateAreaEventArgs e)
        {

            DevExpress.XtraPrinting.TextBrick brick;

            brick = e.Graph.DrawString("CÔNG NỢ KHÁCH HÀNG", Color.Black, new RectangleF(0, 0, 725, 40), DevExpress.XtraPrinting.BorderSide.None);

            brick.Font = new Font("Tahoma", 22);

            brick.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat(StringAlignment.Center);

        }
        private void btnAddMoney_Click(object sender, EventArgs e)
        {

            if (lblCustomerId.Text == "")
            {
                MessageBox.Show("Chọn khách hàng");
                return;
            }
            if (Application.OpenForms["FrmAddMorePaid"] == null)
            {
                FrmAddMorePaid area = new FrmAddMorePaid();
                area.ShowDialog();
                this.AddMoreMoney();
                this.LoadAllItemByCustomerId(int.Parse(lblCustomerId.Text));
                this.UpdateLabelTotal(int.Parse(lblCustomerId.Text));
                this.GetHistoryCustomerPaid(int.Parse(lblCustomerId.Text));
                return;

            }
            Application.OpenForms["FrmAddMorePaid"].ShowDialog();
            this.AddMoreMoney();

        }

        private void AddMoreMoney()
        {
            if (General.addPaidAmount <= 0)
            {
                
                return;
            }
            if (string.IsNullOrEmpty(lblCustomerId.Text))
            {
                MessageBox.Show("Chọn khách hàng");
                return;
            }
            var model = new CustomerPaidHistoryModel();
            model.Amount = General.addPaidAmount;
            model.CustomerId = int.Parse(lblCustomerId.Text);
            model.DateCreate = DateTime.Now.Date;
            model.DatePaid = DateTime.Now.Date;
            model.LastUpdate = DateTime.Now.Date;
            model.UserCreate = General.userName;
            model.UpdateBy = General.userName;
            model.IsEnd = false;
            model.IsHaveItems = false;
            model.CustomerPaidHistoryId = 0;
           var result = wareHouseService.AddMoreMoney(model);
            if (result.CustomerPaidHistoryId > 0 )
            {
                MessageBox.Show("Trả thêm thành công");
                return;
            }
            MessageBox.Show("Trả thêm thất bại");
        }
        private void PrintListItemInGrid(GridControl gridControl)
        {
            PrintableComponentLink printLink = new PrintableComponentLink();
            printLink.CreateReportHeaderArea += this.printLink_CreateReportHeaderArea;

            PrintingSystem printingSystem = new PrintingSystem();
            printingSystem.Links.AddRange(new object[] { printLink });
            printLink.PaperKind = PaperKind.A4;
            printLink.Component = gridControl;

            printLink.Images.Add(Properties.Resources.Logo);

            printLink.Margins.Top = 200;
            printLink.Margins.Left = 25;
            printLink.Margins.Right = 25;


            var agencyName = "";
            var agencyAddress = "";
            var agencyPhone = "";
            var customerName = "";
            var customerAddress = "";
            var customerPhone = "";

            if (lblCustomerId.Text !="")
            {
                var customer = wareHouseService.GetCustomerByCustomerId(int.Parse(lblCustomerId.Text));
                if (customer!=null)
                {
                    customerAddress = customer.Address;
                    customerName = customer.FullName;
                    customerPhone = customer.Phone;
                }
                if (customer == null)
                {
                    MessageBox.Show("Hiện tại chưa có khách hàng được chọn");
                    return;
                }
             
            }
            var currentAgency = wareHouseService.GetCurrentAgency();
            if (currentAgency==null)
            {
                MessageBox.Show("Hiện tại chưa có đại lý nào được chọn");
                return;
            }

            agencyAddress = currentAgency.AgencyAddress;
            agencyName = currentAgency.AgencyName;
            agencyPhone = currentAgency.Phone;
            #region Define content of header
            PageHeaderArea pgHArea = new PageHeaderArea();

            pgHArea.Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Regular);

            pgHArea.Content.AddRange(
                new string[]
                    {
                        "Đại lý : "+ agencyName+ Environment.NewLine 
                        + "Địa chỉ : "+agencyAddress + Environment.NewLine
                        + "Điện thoại : "+agencyPhone + Environment.NewLine + "  " + Environment.NewLine
                        + "Tên khách hàng : "+customerName + Environment.NewLine 
                        + "Địa chỉ : "+customerAddress
                        + Environment.NewLine + "Điện Thoại : "+customerPhone + Environment.NewLine + "" + Environment.NewLine + ""
                        + Environment.NewLine, Environment.NewLine + Environment.NewLine + "", "[Image 0]"
                    });

            #endregion
            #region Define content of footer
            PageFooterArea pgFArea = new PageFooterArea();

            pgFArea.Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Bold);

            pgFArea.Content.AddRange(
                new string[]
                    {"","",
                        "Tổng cộng nợ từ : "+ String.Format("{0:dd/MM/yyyy}",General.DebtDateFrom)+ " đến "+String.Format("{0:dd/MM/yyyy}",General.DebtDateTo)+Environment.NewLine
                    +"Khách hàng ký tên xác nhận"
                      
                  
                    });

            #endregion

            // Create a PageHeaderFooter object for this link.
            printingSystem.Links[0].PageHeaderFooter = new PageHeaderFooter(pgHArea, pgFArea);
        

            printLink.ShowPreview();
        }

       

        private void CreateSummaryForGrid()
        {
            // delete all summary
            gridView2.Columns["TotalWithNotTax"].Summary.Clear();
            gridView2.Columns["TotalWithTax"].Summary.Clear();
            gridView2.Columns["Price"].Summary.Clear();
            
            // just header text
            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Thành tiền chưa lãi suất");
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", "Thành tiền với lãi suất");

            // value
            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Sum, "TotalWithNotTax", "{0:#,###} VND");
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Sum, "TotalWithTax", "{0:#,###} VND");

            // total debt from to -------------------------------

            // text
            gridView2.Columns["Price"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "Price", " ");
            gridView2.Columns["Price"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "Price", " ");
            gridView2.Columns["Price"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "Price", "Tổng cộng nợ từ :");
            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", string.Format("{0:dd/MM/yyyy}", General.DebtDateFrom) + " tới " + string.Format("{0:dd/MM/yyyy}", General.DebtDateTo));
            // value
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", string.Format("{0:#,###} VND", General.TotalFromTo));
            // old debt ------------------------------

            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Nợ cũ :");
            // value
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", string.Format("{0:#,###} VND", General.TotalOldDebt));

            // total old and debt ------------------------------

            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Tổng nợ cũ và mới :");
            // value
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", string.Format("{0:#,###} VND", General.TotalOldAndNew));

            // total paid ------------------------------

            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Đã trả:");
            // value
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", string.Format("{0:#,###} VND", General.TotalPaid));

            // still debt ------------------------------

            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Còn nợ lại:");
            // value
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", string.Format("{0:#,###} VND", General.TotalDebt));


        }

        private void CreateAgainSummaryForGrid()
        {
            // delete all summary
            gridView2.Columns["TotalWithNotTax"].Summary.Clear();
            gridView2.Columns["TotalWithTax"].Summary.Clear();
            gridView2.Columns["Price"].Summary.Clear();

            // just header text
            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithNotTax", "Thành tiền chưa lãi suất");
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Average, "TotalWithTax", "Thành tiền với lãi suất");

            // value
            gridView2.Columns["TotalWithNotTax"].Summary.Add(DevExpress.Data.SummaryItemType.Sum, "TotalWithNotTax", "{0:#,###} VND");
            gridView2.Columns["TotalWithTax"].Summary.Add(DevExpress.Data.SummaryItemType.Sum, "TotalWithTax", "{0:#,###} VND");

            // total debt from to -------------------------------

        


        }

        private void btnEndDebt_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc là muốn tất sổ các hóa đơn này ?","Thông báo",MessageBoxButtons.YesNo,MessageBoxIcon.Question)== DialogResult.Yes)
            {
                if (lblCustomerId.Text=="")
                {
                    MessageBox.Show("Chọn khách hàng");
                    return;
                }
                if (listCustomerDebtModel.Count <=0 )
                {
                    MessageBox.Show("Chưa có công nợ");
                    return;
                }
                listDetailCustomerPaidHistory=new List<DetailCustomerPaidHistoryModel>();
                listExportModel=new List<ExportModel>();
                customerPaidHistoryModel=new CustomerPaidHistoryModel();

                //build list customer

                  var listExportFilter =
                    listCustomerDebtModel.Select(x => x.ExportId).Distinct();
                    listExportModel = listExportFilter.Select(x => new ExportModel { ExportId = x }).ToList();
                
                // build customer paid history model
                customerPaidHistoryModel.Amount = totalAmount - totalPaid;
                customerPaidHistoryModel.CustomerId = int.Parse(lblCustomerId.Text);
                customerPaidHistoryModel.IsEnd = true;
                customerPaidHistoryModel.IsHaveItems = true;
                customerPaidHistoryModel.DateCreate = DateTime.Now;
                customerPaidHistoryModel.LastUpdate = DateTime.Now;
                customerPaidHistoryModel.UpdateBy = General.userName;
                customerPaidHistoryModel.UserCreate = General.userName;
                customerPaidHistoryModel.DatePaid = DateTime.Now;

            
                    // build listDetailCustomerPaidHistory
                foreach (var item in listCustomerDebtModel)
                {
                    listDetailCustomerPaidHistory.Add(
                        new DetailCustomerPaidHistoryModel
                            {
                                DateCreate = DateTime.Now,
                                ItemId = item.ItemId,
                                ItemName = item.ItemName,
                                LastUpdate = DateTime.Now,
                                Price = item.Price,
                                Quantity = item.Quantity,
                                TaxRate = (decimal)item.TaxRate,
                                TotalWithNotTax = item.TotalWithNotTax,
                                TotalWithTax = item.TotalWithTax,
                                UpdateBy = General.userName,
                                UserCreate = General.userName,
                                ExportId = item.ExportId
                                
                            });


                   //excute


                }


                var result = wareHouseService.EndDebtForCustomer(
                     listDetailCustomerPaidHistory, customerPaidHistoryModel, listExportModel);

                if (result)
                {
                    MessageBox.Show("Tất sổ thành công");
                    if (lblCustomerId.Text.Trim() != "")
                    {
                        UpdateLabelTotal(int.Parse(lblCustomerId.Text));
                        //refresh grid
                        listCustomerDebtModel = new List<CustomerDebtModel>();
                        gridItem.DataSource = listCustomerDebtModel.ToArray();
                        this.UpdateLabelTotal(int.Parse(lblCustomerId.Text));
                        this.GetHistoryCustomerPaid(int.Parse(lblCustomerId.Text));
                    }
                
                    return;
                }
                MessageBox.Show("Có lỗi thiết bị khi tất sổ vui lòng kiểm tra lại");

            }
        }

        private void panel4_Paint(object sender, PaintEventArgs e)
        {

        }

        private void gridView3_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                var modelCustomerPaid = (CustomerPaidHistoryModel)gridView3.GetRow(gridView3.GetSelectedRows()[0]);
                if (modelCustomerPaid != null)
                {

                    var result = this.wareHouseService.GetDetailCustomerPaidHistoryByCustomerPaidHistoryId(modelCustomerPaid.CustomerPaidHistoryId);
                    this.gridItem.DataSource = result.ToArray();
                    General.DebtDateFrom = result.Select(x => x.DateCreate).Distinct().Min(x => x.Date).Date;
                    General.DebtDateTo = result.Select(x => x.DateCreate).Distinct().Max(x => x.Date).Date;
                    CreateAgainSummaryForGrid();
                    btnEndDebt.Enabled = false;
                }
            }
            catch (Exception)
            {


            }
        }

        private void btnPrintAgain_Click(object sender, EventArgs e)
        {
            this.PrintListItemInGrid(gridItem);
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void CheckRole()
        {
            if (!wareHouseService.R(General.groupUserId, "managedebt_addmore"))
            {
                btnAddMoney.Enabled = false;

            }
            if (!wareHouseService.R(General.groupUserId, "managedebt_finish"))
            {
                btnEndDebt.Enabled = false;

            }
            if (!wareHouseService.R(General.groupUserId, "managedebt_print"))
            {
                btnPrintAgain.Enabled = false;

            }

         
            

        }

      
    }
}
